//纯信息  activeItem.type:1  做信息敏感词过滤
//纯图片 activeItem.type：11 
//修复 重构  优化算法
const onmessage = (activeItem, token) => {
	activeItem.createTime = getdate();
	console.log("信息activeItem", activeItem);
	let obj = {
		code: 200,
		type: 1, //1：message:2：relationship,3：online
		message: "charMsg",
		data: {}
	}
	let sendSuccess = {
		code: 200,
		type: 7,
		status: true,
		message: "success"
	}
	let sendError = {
		code: 200,
		type: 7,
		status: false,
		message: "error"
	}
	try {
		if (!activeItem.type||!activeItem.fromId || !activeItem.fromName || !activeItem.fromUrl || !activeItem.activeId || !activeItem
			.message || activeItem.isGroup === undefined || activeItem.msglength === undefined) {
			obj.message = "未按要求传参";
			obj.code = 201;
			throw new Error(obj.message);
		}
		let send = Object.assign(obj, {
			data: activeItem
		});
		//添加消息 纯文本
		let sql =
			`INSERT INTO message(\`Id\`, \`msg\`, \`userId\`, \`otherId\`, \`isGroup\`, \`status\`,\`type\`,\`imagesUrl\`, \`createTime\`, \`updateTime\`,\`dirimagesUrl\`,\`msglength\`) VALUES (null, '${activeItem.message}', ${activeItem.fromId},${activeItem.activeId},${activeItem.isGroup},1,${activeItem.type},'${activeItem.imagesUrl}', '${activeItem.createTime}', '${activeItem.createTime}','','${activeItem.msglength}')`;
		let paramsList = lastMsg = ""
		
		if (activeItem.type == 1) {
			lastMsg = activeItem.message.substring(0, 13);
			lastMsg = activeItem.message.length > 14 ? lastMsg + '...' : lastMsg;
		} else {
			sql =
				`INSERT INTO message(\`Id\`, \`msg\`, \`userId\`, \`otherId\`, \`isGroup\`, \`status\`,\`type\`,\`imagesUrl\`, \`createTime\`, \`updateTime\`,\`dirimagesUrl\`,\`msglength\`) 
				VALUES (null, '[图片]', ${activeItem.fromId},${activeItem.activeId},${activeItem.isGroup},1,${activeItem.type},
				'${activeItem.imagesUrl}', '${activeItem.createTime}', '${activeItem.createTime}','','0')`;
			lastMsg = "[图片]"
		}
		//修改联系人最后一条信息的时间和信息
		let updateSQL = "";
		if (activeItem.isGroup === 1) {
			//群组 群发
			updateSQL =
				`update grouplastmsg set lastMessage='${lastMsg}',updateTime='${activeItem.createTime}' where groupId=${activeItem.activeId} and status=1`

			if (activeItem.activeId === 1 || activeItem.isneed === 1) {
				//id 1 为所有人必进的群 all推送
				WSsendAll(send)
				messageSend(sql, updateSQL, activeItem.fromId, token, sendSuccess,
					sendError)
			} else {
				//获取群人数
				let selectSql = `select userlist from  shsgroup where Id= ${activeItem.activeId} and status=1;`;
				shsDB(selectSql).then(data => {
					if (data.length === 0) {
						throw new Error("data.length===0");
					}
					if (data[0].userlist === undefined || data[0].userlist === null) {
						throw new Error("userlist is null");
					}
					let userlist = data[0].userlist.split(',');
					for (let i = 0; i < userlist.length; i++) {
						WSsendMessage(send, userlist[i])
					}
					WSsendMessage(sendSuccess, activeItem.fromId)
					messageSend(sql, updateSQL, activeItem.fromId, token,
						sendSuccess, sendError)
				}).catch(err => {
					obj.code = 201;
					if (err.message === "userlist is null") {
						obj.message = "数据不合法"
					}
					if (err.message === "data.length===0") {
						obj.message = "群聊已封禁或不存在"
					} else {
						obj.message = err.message
						console.log("err 群消息推送", err)
					}
					sendError.message = obj.message;
					WSsendMessage(sendError, activeItem.fromId)
				})
			}

		} else {
			// 单发
			updateSQL =
				`update relationshipuser set lastMessage='${lastMsg}',updateTime='${activeItem.createTime}' where (userId=${activeItem.fromId} and otherId=${activeItem.activeId}) or (userId=${activeItem.activeId} and otherId=${activeItem.fromId}) and status=1`
			//接收者
			WSsendMessage(send, activeItem.activeId)
			messageSend(sql, updateSQL, activeItem.fromId, token, sendSuccess,
				sendError)
		}

	} catch (e) {
		sendError.message = e.message;
		WSsendMessage(sendError, activeItem.fromId)
	}
}
/**
 * sql存储 新增信息 修改最后一条信息记录
 * 
 */
function messageSend(sql, updateSQL, fromId, token, sendSuccess, sendError) {
	shsDB(sql).then(data => {
		try {
			upIntegral(fromId, 1) //增加积分
		} catch (e) {}
		return shsDB(updateSQL)
	}).then(data => {
		console.log("信息添加成功", fromId, sendSuccess, token);
		WSsendMessage(sendSuccess, fromId, token)
	}).catch(err => {
		console.log("err 信息添加", err);
		sendError.message = err.message;
		WSsendMessage(sendError, fromId, token)
	})
}

module.exports = onmessage